import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/i18n/i18n.dart';
import 'package:qunaimedical/models/statistics.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/utils/sp_utils.dart';

/// 状态管理
class Store {
  Store._internal();

  // 全局初始化
  static init(Widget child) {
    return MultiProvider(
      providers: [
        // 国际化
        ChangeNotifierProvider.value(
          value: LocaleStore(SPUtils.getLanguageCode()),
        ),
        // 全局信息
        ChangeNotifierProvider.value(
          value: StoreInfo(SPUtils.getUser(), Statistics(), 0),
        ),
      ],
      child: child,
    );
  }
}

/// 语言
class LocaleStore with ChangeNotifier {
  String _languageCode;

  LocaleStore(this._languageCode);

  String get languageCode => _languageCode;

  set languageCode(String languageCode) {
    if (languageCode != null && languageCode != _languageCode) {
      _languageCode = languageCode;
      S.locale = Locale(languageCode);
      SPUtils.setLanguageCode(languageCode);
      notifyListeners();
    }
  }

  void setLanguageCode(String languageCode) {
    _languageCode = languageCode;
    SPUtils.setLanguageCode(languageCode);
  }
}

/// 全局信息
class StoreInfo with ChangeNotifier {
  User _user;

  /// 统计信息
  Statistics _statistics;

  int _unreadMsgCount;

  /// 未读消息个数
  int get unreadMsgCount => _unreadMsgCount;

  void updateUnreadMsgCount(int value) {
    _unreadMsgCount = value;
    notifyListeners();
  }

  StoreInfo(this._user, this._statistics, this._unreadMsgCount);

  User get user => _user;

  Statistics get statistics => _statistics;

  void updateUser(User value) {
    _user = value;
    SPUtils.setUser(value);
    notifyListeners();
  }

  void updateStatistics(Statistics statistics) {
    _statistics = statistics;
    notifyListeners();
  }

  /// 清空全局信息
  void clear() {
    _user = null;
    SPUtils.setUser(null);
    _statistics = Statistics();
    _unreadMsgCount = 0;
    notifyListeners();
  }
}
